<script lang="ts" setup>
import { getCourseInformationById, getSourceFileUrlApi, updateCourseStudyRecordApi } from '@/api/study/course';
import { useStudyRecordStore } from '@/stores/studyRecordStore';
import { message } from 'ant-design-vue';
import { nextTick, onBeforeMount, onMounted, ref, watch } from 'vue';
import vue3videoPlay from 'vue3-video-play'; // 导入 vue3-video-play 组件
import 'vue3-video-play/dist/style.css'; // 引入样式文件

const props = defineProps({
  courseId: {
    type: String,
    required: true,
  },
  sourceId: {
    type: String,
    required: true,
  },
});

const playerRef = ref<any>(null); // 定义播放器引用
const sourceFileUrl = ref<string | null>('');
const studyRecordStore = useStudyRecordStore();
const courseName = ref<string>('');

// 定时器
let timer: any | null = null;
let watchTime = 0;
// 发送学习记录
const sendStudyRecord = async () => {
  try {
    const response = await updateCourseStudyRecordApi(props.sourceId);
    studyRecordStore.setStudyRecordData(response);
    watchTime = 0;
  }
  catch (error) {
    message.error("发送学习记录失败");
  }
};

// 播放器开始播放时触发发送学习记录
const startTimer = () => {
  timer = setInterval(() => {
    watchTime += 1;
    if (watchTime % 60 === 0)
      sendStudyRecord();
  }, 1000);
};

// 停止计时
const stopTimer = () => {
  if (timer) {
    clearInterval(timer);
    timer = null;
  }
};

// 获取课程名称
const fetchCourseName = async () => {
  try {
    const response = await getCourseInformationById(props.courseId);
    courseName.value = response.courseName;
  }
  catch (error) {
    message.error("获取课程元信息失败");
  }
};

// 获取具体资源URL
const fetchSourceFileInfo = async (sourceId: string) => {
  try {
    const response = await getSourceFileUrlApi(sourceId);
    sourceFileUrl.value = response;

    // 更新播放器数据源
    if (playerRef.value) {
      const videoElement = playerRef.value.$el.querySelector('video') as HTMLVideoElement | null;
      if (videoElement) {
        videoElement.src = response;
        // videoElement.load();

        // 监听 loadedmetadata 事件，确保视频元数据加载完成
        videoElement.addEventListener('loadedmetadata', () => {
          // 视频元数据加载完成
        });
      }
      else {
        message.error("视频元素未找到。");
      }
    }
  }
  catch (error) {
    message.error("获取资源信息失败");
  }
};

// 监听 props.sourceId 的变化，更新资源 URL
watch(() => props.sourceId, (newSourceId: string) => {
  fetchSourceFileInfo(newSourceId);
});

// 初始化时获取资源信息、评论数据和课程名称
onMounted(() => {
  fetchSourceFileInfo(props.sourceId);
  startTimer();
  fetchCourseName();

  // 确保在下一个 tick 中获取播放器实例
  nextTick(() => {
    if (playerRef.value) {
      const videoElement = playerRef.value.$el.querySelector('video') as HTMLVideoElement | null;
      if (videoElement) {
        // 播放器实例已获取
      }
      else {
        // 视频元素未准备好
      }
    }
    else {
      // PlayerRef 未设置
    }
  });

  // 初始化获取课程名称
  fetchCourseName();
});

// 组件销毁前清理
onBeforeMount(() => {
  stopTimer();
  // 超过40秒也算一次发送学习记录
  if (watchTime > 40)
    sendStudyRecord();
});
</script>

<template>
  <div class="video-player-container">
    <!-- 视频播放部分 -->
    <div class="video-container">
      <vue3videoPlay
        ref="playerRef"
        width="100%"
        height="60vh"
        :src="sourceFileUrl"
      />
    </div>
  </div>
</template>

<style scoped lang="scss">
.video-player-container {
  padding: 1rem;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  max-width: 100%;
  box-sizing: border-box;
  height: 100%;
}

.video-container {
  position: relative;
  margin-top: 2rem;
  width: 100%;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .video-player-container {
    padding: 0.5rem;
  }

  .header {
    .course-title {
      font-size: 1.2rem;
    }
  }
}
</style>
